package org.misalen.web.database.repository.mysql;

import org.hibernate.Query;
import org.hibernate.Session;
import org.misalen.web.database.dao.mysql.impl.BaseMySqlDaoImpl;
import org.misalen.web.database.model.mysql.pro.ProDriverUser;
import org.springframework.stereotype.Repository;

@Repository
public class ProDriverUserRepository extends BaseMySqlDaoImpl<ProDriverUser> {

	public long countByMobile(String mobile) {
		String hql = "select count(*) from ProDriverUser where mobile=?0";
		return count(hql, new Object[] { mobile });
	}

	public ProDriverUser findByMobilePwd(String mobile, String password) {
		String hql = "from ProDriverUser where mobile=?0 and password=?1";
		return get(hql, new Object[] { mobile, password });
	}

	public ProDriverUser findByMobileImei(String mobile, String imei) {
		String hql = "from ProDriverUser where mobile=?0 and imei=?1";
		return get(hql, new Object[] { mobile, imei });
	}

	public ProDriverUser findByMobile(String mobile) {
		String hql = "from ProDriverUser where mobile=?0";
		return get(hql, new Object[] { mobile });
	}

	public void updateFreezeBalance(Integer money, String primaryKey) {
		String sql = "update ProDriverUser set freezeBalance=freezeBalance ";
		if (money > 0) {
			sql += "+" + money;
		} else {
			sql += "-" + (-money);
		}
		sql += " where primaryKey='" + primaryKey + "'";
		Session session = this.openSession();
		Query query = session.createQuery(sql);
		query.executeUpdate();
		closeSession(session);
	}

	public void updateTodayIncome(Integer money) {
		String sql = "update ProDriverUser set todayIncome= " + money;
		Session session = this.openSession();
		Query query = session.createQuery(sql);
		query.executeUpdate();
		closeSession(session);
	}

	public void updateWithDraw(Integer money, String primaryKey) {
		String sql = "update ProDriverUser set withdrawal=withdrawal ";
		if (money > 0) {
			sql += "+" + money;
		} else {
			sql += "-" + (-money);
		}
		sql += " where primaryKey='" + primaryKey + "'";
		Session session = this.openSession();
		Query query = session.createQuery(sql);
		query.executeUpdate();
		closeSession(session);
	}

	public void updateBalance(Integer money, String primaryKey) {
		String sql = "update ProDriverUser set balance=balance ";
		if (money > 0) {
			sql += "+" + money;
		} else {
			sql += "-" + (-money);
		}
		sql += " where primaryKey='" + primaryKey + "'";
		Session session = this.openSession();
		Query query = session.createQuery(sql);
		query.executeUpdate();
		closeSession(session);
	}

	public ProDriverUser findByMachine(String machineId, String type) {
		String hql="from ProDriverUser";
		if(type.equals("headrest")){
			hql+=" where headrestCode=?0";
		}else{
			hql+=" where backseatCode=?0";
		}
		return get(hql, new Object[]{machineId});
	}
}